package cmlabs.moduloariphmetics;

/**
 * Created by IntelliJ IDEA.
 * User: jte
 * Date: 14.4.11
 * Time: 22.35
 * To change this template use File | Settings | File Templates.
 */
public class PrimeField implements Field {

    public PrimeField(int p){
        this.p = p;
    }

    public int reverseElement(int a) {
        if (a == 0){
            throw new IllegalArgumentException();
        }
        return (int)cmlabs.numbertheoryutils.Functions.powMod(a, p - 2, p);
    }

    public int add(int a, int b) {
       return (a % p + b % p) % p;
    }

    public int multiply(int a, int b) {
        return (a % p * b % p) % p;
    }

    public int divide(int a, int b) {
        if (b == 0){
            throw new IllegalArgumentException("division by zero");
        }
        return multiply(a, reverseElement(b));
    }

    public int subtract(int a, int b) {
        return  (a % p + p - b % p) % p;
    }

    private int p;
}
